const Subscription = require('egg').Subscription;

const fs = require("fs");

//放弃了， 不整了，调亮总的

class SendTicketSmsCache extends Subscription {

	static get schedule() {

		return {
			interval: '30s',
			type: 'worker',
			immediate: true,

			disable: true,
		};
	}


	async subscribe() {

		const { ctx, app } = this;

		ctx.app.logger.info('退票定时任务开始');

		try{
			const toBeRefundList = await ctx.service.order.getToBeRefundList();

			for(let i = 0; i < toBeRefundList.length; i++){
				const order = toBeRefundList[i];

				const payinfo = await ctx.service.pay.getPayInfo(order.pay_trade_no);

				//if(payinfo.amount != order.)
				
				const p = {
					wxid : payinfo.wxid, 
					transaction_id : order.pay_trade_no, 
					out_refund_no : order.id,
					total_fee : order.pay_fee, 
					refund_fee : order.back_price, 
				};

				const xml = await ctx.service.weixin.refund(p);

				ctx.logger.info(xml);

				const wxinfo = await ctx.service.company.infoByWXid(payinfo.wxid);



				const result = await ctx.curl('https://api.mch.weixin.qq.com/secapi/pay/refund', {
		            method: 'POST',
		            body: xml,
		            //dataType: 'text',
            		//dataType: 'text',
		            //dataType: 'text/xml',
		   //          agentOptions: {
	    //  //        		cert: fs.readFileSync('http://weshop88.oss-cn-hangzhou.aliyuncs.com/apiclient_cert.pem'),
					// 	// key:  fs.readFileSync('http://weshop88.oss-cn-hangzhou.aliyuncs.com/apiclient_key.pem'),
					// 	cert: fs.readFileSync('./apiclient_cert.pem'),
					// 	key:  fs.readFileSync('./apiclient_key.pem'),
					// 	// pfx : fs.readFileSync('./wx_cert.p12'),
					// 	// passphrase : wxinfo.mch_id,
					// },
					headers: {
					    'content-type': 'xml',
					    'Content-Length': xml.length
					},
		        });

				ctx.logger.info(result);

			}
		}catch(err){

			ctx.app.logger.info('------ 异常 -------');
			ctx.app.logger.info(err);
			
		}

		ctx.app.logger.info('退票定时任务结束');

	}

}

module.exports = SendTicketSmsCache;